import { Byte } from '../../api/io/Byte';
import { BattleReportInfo } from './BattleReportInfo';
import { HashMap } from '../../api/struct/HashMap';
import { BattleReportCamp } from './BattleReportCamp';
import { ITimer } from '../../api/timer/ITimer';
import { IAsync } from '../../api/event/IAsync';
import { MathUtils } from '../../api/math/MathUtils';



/**战报属性枚举*/
export const enum E_BattleReport {
	/**战斗id*/
	BATTLE_ID = 0,
	/**客户端战斗*/
	RUN_IN_CLIENT = 1,
	/**信息*/
	INFO = 2,
	/**阵容*/
	CAMP = 3,
	/**枚举数量*/
	EnumCount = 4
}


/**战报*/
export class BattleReport {
	/**事件ID*/
	public static readonly EVENT_ID = 'STRUCT_DATA_BATTLE_REPORT_EVENT_ID';
	/**整体更新事件ID（部分只需要监听整体变化）*/
	public static readonly TOTAL_EVENT_ID = 'STRUCT_DATA_BATTLE_REPORT_TOTAL_EVENT_ID';
	/**缓存池*/
	private static POOL: BattleReport[] = [];

	/**创建入口*/
	public static create(json?: string): BattleReport {
		const c = this.POOL.pop() || new BattleReport();
		c._destroyed = false;
		c.resetProperty();
		if (json) {
			c.parse(json);
		}
		return c;
	}


	/**已释放*/
	protected _destroyed = false;
	/**战斗id (long)*/
	protected _battleId: number;
	/**客户端战斗*/
	protected _runInClient: boolean;
	/**信息*/
	protected _info: BattleReportInfo = null;
	/**阵容*/
	protected _camp: HashMap<number, BattleReportCamp> = null;


	/**构建函数-私有，防止外部创建*/
	private constructor() {
	}


	/**释放*/
	public destroy(): void {
		if (this._destroyed) {
			return;
		}
		this._destroyed = true;
		this.resetProperty(true);
		if (BattleReport.POOL.indexOf(this) === -1) {
			BattleReport.POOL.push(this);
		}
	}

	/**战斗id*/
	public get battleId() {
		return this._battleId;
	}


	/**战斗id*/
	public set battleId(v: number) {
		this._battleId = v;
	}


	/**客户端战斗*/
	public get runInClient() {
		return this._runInClient;
	}


	/**客户端战斗*/
	public set runInClient(v: boolean) {
		this._runInClient = v;
	}


	/**信息*/
	public get info() {
		return this._info;
	}


	/**设置阵容*/
	public putCamp(k: number, v: BattleReportCamp): BattleReportCamp {
		const ov = this._camp.put(k, v);
		return ov;
	}


	/**获取阵容*/
	public getCamp(k: number) {
		return this._camp.get(k);
	}


	/**删除阵容*/
	public removeCamp(k: number, autoDestroy = false): BattleReportCamp {
		const ov = this._camp.remove(k);
		if (autoDestroy && ov) {
			ov.destroy();
		}
		return ov;
	}


	/**获取阵容映射表-键值(外部改变将导致出错，只能用于遍历)*/
	public getCampKeys(): number[] {
		return this._camp.getKeys();
	}


	/**获取阵容映射表-值(外部改变将导致出错，只能用于遍历)*/
	public getCampValues(): BattleReportCamp[] {
		return this._camp.getValues();
	}


	/**清空阵容映射表*/
	public clearCampMap(autoDestroy = false): void {
		const ks = this._camp.getKeys();
		for (let i = ks.length - 1; i >= 0; i--) {
			this.removeCamp(ks[i], autoDestroy);
		}
	}



	/**通过枚举获取值*/
	public getV(k: E_BattleReport): any {
		switch (k) {
			case E_BattleReport.BATTLE_ID: return this._battleId;
			case E_BattleReport.RUN_IN_CLIENT: return this._runInClient;
			case E_BattleReport.INFO: return this._info;
			case E_BattleReport.CAMP: return this._camp;
			default: return null;
		}
	}


	/**通过枚举设置值*/
	public setV(k: E_BattleReport, v: any): void {
		switch (k) {
			case E_BattleReport.BATTLE_ID: this._battleId = v; break;
			case E_BattleReport.RUN_IN_CLIENT: this._runInClient = v; break;
			case E_BattleReport.INFO: this._info = v; break;
			case E_BattleReport.CAMP: this._camp = v; break;
			default: break;
		}
	}


	/**初始化*/
	public resetProperty(fromDestroy = false): void {
		//战斗id
		this._battleId = 0;
		//客户端战斗
		this._runInClient = false;
		//信息
		if (this._info) {
			this._info.destroy();
			this._info = null;
		}
		if (!fromDestroy) {
			this._info = BattleReportInfo.create();
		}
		//阵容
		if (this._camp) {
			const list = this._camp.getValues();
			for (let i = 0, len = list.length; i < len; i++) {
				list[i].destroy();
			}
			this._camp.clear();
		}
		else {
			this._camp = new HashMap<number, BattleReportCamp>();
		}
	}


	/**序列化*/
	public stringify(toString: boolean): string | any {
		const json: any = {};
		if (this._battleId) {
			json.battleId = this._battleId;
		}
		if (this._runInClient) {
			json.runInClient = this._runInClient;
		}
		if (this._info) {
			json.info = this._info.stringify(false);
		}
		if (this._camp.size() > 0) {
			const ks = this._camp.getKeys();
			const vs = this._camp.getValues();
			const list: string[] = [];
			for (let i = 0, len = vs.length; i < len; i++) {
				list[i] = vs[i].stringify(false);
			}
			json.camp = [ks, list];
		}

		return toString ? JSON.stringify(json) : json;
	}


	/**反序列化*/
	public parse(jsonv: string | any): this {
		this.resetProperty();
		if (!jsonv) {
			return this;
		}
		const json = typeof (jsonv) === 'string' ? JSON.parse(jsonv) : jsonv;
		if (json.battleId) {
			this._battleId = json.battleId;
		}
		if (json.runInClient) {
			this._runInClient = json.runInClient;
		}
		if (json.info) {
			this._info.destroy();
			this._info = BattleReportInfo.create(json.info);
		}
		if (json.camp) {
			const ks: number[] = json.camp[0] || (json.camp.getKeys ? json.camp.getKeys() : null);	//对象可能是json或者结构体
			const vs: string[] = json.camp[1] || (json.camp.getValues ? json.camp.getValues() : null);
			if (ks && vs && ks.length === vs.length) {
				for (let i = 0, len = vs.length; i < len; i++) {
					this._camp.put(ks[i], BattleReportCamp.create(vs[i]));
				}
			}
		}
		return this;
	}


	/**序列化-二进制*/
	public toBytes(byte: Byte): void {
		if (!byte) {
			return;
		}
		byte.writeLongNumber(this._battleId);
		byte.writeBool(this._runInClient);
		this._info.toBytes(byte);
		//阵容
		{
			const ks = this._camp.getKeys();
			const vs = this._camp.getValues();
			const len = ks.length;
			byte.writeUint16(len);
			for (let i = 0; i < len; i++) {
				byte.writeUint8(ks[i]);
				vs[i].toBytes(byte);
			}
		}
	}


	/**反序列化-二进制*/
	public fromBytes(byte: Byte): this {
		this.resetProperty();
		if (!byte) {
			return;
		}
		this._battleId = byte.readLongNumber();
		this._runInClient = byte.readBool();
		this._info.fromBytes(byte);
		//阵容
		{
			const len = byte.readUint16();
			for (let i = 0; i < len; i++) {
				const k = byte.readUint8();
				const v = BattleReportCamp.create();
				v.fromBytes(byte);
				this._camp.put(k, v);
			}
		}
		return this;
	}


	/**克隆*/
	public clone(): BattleReport {
		const byte = Byte.createFromPool();
		this.toBytes(byte);
		byte.pos = 0;
		const clonev = BattleReport.create().fromBytes(byte);
		Byte.recoverToPool(byte);
		return clonev;
	}


	/**处理更新*/
	public processUpdate(jsonv: string): void {
		if (!jsonv) {
			return;
		}

		const eventID = BattleReport.EVENT_ID;
		const us = JSON.parse(jsonv);

		for (let i = 0, len = us.length; i < len;) {
			const idx = us[i];
			//战斗id
			if (idx === E_BattleReport.BATTLE_ID) {
				const oldv = this._battleId;
				this._battleId = us[i + 1];
				IAsync.dispatch(eventID, idx, this._battleId, oldv);
				i += 2;
				continue;
			}
			//客户端战斗
			if (idx === E_BattleReport.RUN_IN_CLIENT) {
				const oldv = this._runInClient;
				this._runInClient = us[i + 1];
				IAsync.dispatch(eventID, idx, this._runInClient, oldv);
				i += 2;
				continue;
			}
			//信息
			if (idx === E_BattleReport.INFO) {
				const fui: string = us[i + 1];
				if (this._info) {
					this._info.processUpdate(fui);
				}
				else {
					console.error('BattleReport info is null when update.');
				}
				IAsync.dispatch(eventID, idx);
				i += 2;
				continue;
			}

			//阵容
			if (idx === E_BattleReport.CAMP) {
				const k: number = us[i + 1];
				const ctrl: number = us[i + 2];
				if (ctrl === 0) {
					const oldv = this.removeCamp(k);
					if (oldv) {
						oldv.destroy()
					}
				}
				else if (ctrl === 1) {
					const newv = BattleReportCamp.create(us[i + 3]);
					const oldv = this.putCamp(k, newv);
					if (oldv) {
						oldv.destroy()
					}
				}
				else {
					const curv = this.getCamp(k);
					if (curv) {
						curv.processUpdate(us[i + 3]);
					}
					else {
						console.error('BattleReport BattleReportCamp is not exist when update! k = ' + k);
					}
				}
				IAsync.dispatch(eventID, idx, k, ctrl);
				i += ctrl === 0 ? 3 : 4;
				continue;
			}

			console.error('[Struct Data] can not find enum in BattleReport with idx = ' + idx + ', version maybe wrong.')
		}

		//全更事件
		ITimer.callLater(this, this.dispatchTotalUpdate);
	}


	/**比对不一致结果*/
	public getCompareInfo(other: BattleReport): string {
		if (!other) {
			return null;
		}

		const updates: any[] = [];

		if (this._battleId !== other._battleId) {
			updates.push(E_BattleReport.BATTLE_ID, this._battleId);
		}
		if (this._runInClient !== other._runInClient) {
			updates.push(E_BattleReport.RUN_IN_CLIENT, this._runInClient);
		}
		//信息
		{
			const ui = this._info.getCompareInfo(other._info);
			if (ui && ui.length > 0) {
				updates.push(E_BattleReport.INFO, ui);
			}
		}

		//阵容
		{
			const idx = E_BattleReport.CAMP;
			const ks1 = this._camp.getKeys();
			const ks2 = other._camp.getKeys();
			const rs = MathUtils.intersectSortedArray(ks1, ks2);
			if (rs[0].length > 0) {
				const list = rs[0];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getCamp(k);
					const oldv = other.getCamp(k);
					const ui = newv.getCompareInfo(oldv);
					if (ui && ui.length > 0) {
						updates.push(idx, k, 2, ui);
					}
				}
			}
			if (rs[1].length > 0) {
				const list = rs[1];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getCamp(k);
					updates.push(idx, k, 1, newv.stringify(false));
				}
			}
			if (rs[2].length > 0) {
				const list = rs[2];
				for (let i = 0, len = list.length; i < len; i++) {
					updates.push(idx, list[i], 0);
				}
			}
		}

		const jsonv = updates.length === 0 ? null : JSON.stringify(updates);
		return jsonv;
	}


	/**全部更新*/
	protected dispatchTotalUpdate(): void {
		IAsync.dispatch(BattleReport.TOTAL_EVENT_ID, this.getV(0));
	}

}
